/** 图片文件转base64 */
export function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      resolve(reader.result as string);
    };
    reader.onerror = error => {
      reject(error);
    };
  });
}
/** 数据链接转图片 */
export function dataURLtoImg(dataUrl: string): Promise<HTMLImageElement> {
  return new Promise(resolve => {
    const img = new Image();
    img.src = dataUrl;
    img.onload = () => {
      resolve(img);
    };
  });
}
/** canvas转文件 */
export function canvasToFile(canvas: HTMLCanvasElement, type: string): Promise<Blob> {
  return new Promise(resolve => {
    canvas.toBlob(blob => resolve(blob!), type, 1);
  });
}
/**
 * 图片压缩
 * @param {File} file 图片文件
 * @param {Number} quality 压缩的质量
 * @return {File} 压缩后的图片
 */
export async function compressImage(file: File, quality: number) {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d')!;
  const base64Url = await fileToBase64(file);
  const image = await dataURLtoImg(base64Url);
  canvas.width = image.width * quality;
  canvas.height = image.height * quality;
  ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
  const blob = await canvasToFile(canvas, file.type);
  return new File([blob], file.name, {type: file.type});
}
